<template>
  <div class="user-add-or-update">
    <el-drawer :title="this.rowData ? '修改业务规则' : '新增业务规则'" :visible.sync="drawer" custom-class="demo-drawer" direction="rtl" size="50%">
      <div class="demo-drawer__content">
        <div class="rightScrollNone">
          <el-form size="mini" :model="formData" :rules="rules" ref="ruleForm">
            <el-row>
              <el-col :span="24">
                <p>基本信息</p>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="规则名称" prop="name">
                  <el-input placeholder="请输入规则名称" autocomplete="off" type="text" v-model="formData.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="规则描述" prop="desc">
                  <el-input placeholder="最多输入200个字符" maxlength="200" autocomplete="off" type="textarea" v-model="formData.desc"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="适用范围" prop="use_range">
                  <el-radio-group v-model="formData.use_range" @input="handleRadioChange">
                    <el-radio :label="1">指定部门</el-radio>
                    <el-radio :label="2">指定员工</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" prop="range_ids">
                  <el-select v-model="formData.range_ids" multiple collapse-tags placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in selectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-row>
              <el-col :span="24">
                <p>跟踪设置</p>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="跟踪倒计时" prop="is_follow">
                  <el-radio-group v-model="formData.is_follow">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="2">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="tips">
                  <i class="el-icon-warning"></i>
                  <p class="desc">跟踪倒计时结束后仍未腹部信息将自动踢回公海</p>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="" prop="follow_days">
                  <el-input type="Number" min="0" placeholder="请输入天数" v-model="formData.follow_days"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <p class="unit">天</p>
              </el-col>
            </el-row>

            <el-divider></el-divider>
            <el-row>
              <el-col :span="24">
                <p>申领设置</p>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="申领地区" prop="zone_province_list">
                  <el-select v-model="formData.zone_province_list" multiple collapse-tags placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in zoneList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="tips">
                  <i class="el-icon-warning"></i>
                  <p class="desc">申领时仅能申领所选地区的客户</p>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="申领上限" prop="accept_limit">
                  <el-input type="Number" min="0" placeholder="请输入上限个数" v-model="formData.accept_limit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <p class="unit">个</p>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="申领保留倒计时" prop="is_accept_down">
                  <el-radio-group v-model="formData.is_accept_down">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="2">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="tips">
                  <i class="el-icon-warning"></i>
                  <p class="desc">申领保留倒计时结束后仍未跟踪将自动踢回公海</p>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label-width="formLabelWidth" label="" prop="accept_down_days">
                  <el-input type="Number" min="0" placeholder="请输入天数" v-model="formData.accept_down_days"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <p class="unit">天</p>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-row type="flex" justify="end">
          <el-button size="mini" @click="cancelForm">取 消</el-button>
          <el-button size="mini" :loading="loading" @click="formDataSubmit" type="primary">确定</el-button>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { apiRuleAdd, apiRuleEdit, apiRuleSelect } from '@/api/customer'

export default {
  data() {
    var checkFollowDays = (rule, value, callback) => {
      if (this.formData.is_follow === '1' && !value) {
        return callback(new Error('跟踪天数不能为空'))
      } else {
        callback()
      }
    }
    var checkAcceptDownDays = (rule, value, callback) => {
      if (this.formData.is_accept_down === '1' && !value) {
        return callback(new Error('跟踪天数不能为空'))
      } else {
        callback()
      }
    }
    return {
      editType: 'add',
      deparmentList: [],
      userList: [],
      selectList: [],
      zoneList: [],
      formData: {
        name: '', // 名称
        desc: '', // 描述
        use_range: 1, // 适用范围（1：部门；2：员工）
        range_ids: '', // 人或部门id
        is_follow: 1, // 是否开启跟踪（1：开启；2：关闭）
        follow_days: '', // 跟踪天数
        zone_province: '', // 所属地区
        zone_province_list: '', // 所属地区列表
        accept_limit: '', // 接受上限
        is_accept_down: 1, // 是否开始申领倒计时（1：开启；2,：关闭）
        accept_down_days: '', // 申领倒计时天数
      },
      rowData: null,
      formLabelWidth: '150px',
      loading: true,
      drawer: false,
      rules: {
        name: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
        use_range: [{ required: true, message: '适用范围不能为空', trigger: 'blur' }],
        range_ids: [{ required: true, message: '适用范围不能为空', trigger: 'blur' }],
        is_follow: [{ required: true, message: '跟踪倒计时不能为空', trigger: 'blur' }],
        zone_province_list: [{ required: true, message: '申领地区不能为空', trigger: 'blur' }],
        accept_limit: [{ required: true, message: '申领上限不能为空', trigger: 'blur' }],
        is_accept_down: [{ required: true, message: '申领保留倒计时不能为空', trigger: 'blur' }],
        follow_days: [{ validator: checkFollowDays, trigger: 'blur' }],
        accept_down_days: [{ validator: checkAcceptDownDays, trigger: 'blur' }],
      },
    }
  },
  mounted() {
    this.getSelect()
  },
  methods: {
    // 打开弹出层
    open(row) {
      if (this.drawer) {
        return
      }
      this.rowData = row || null
      this.drawer = true
      this.openHook()
    },
    // 数据回显
    openHook() {
      this.$nextTick(() => {
        this.clearData(this.rowData)
        if (this.rowData) {
          // 修改
          this.editType = 'edit'
          this.formData.id = this.rowData.id
        } else {
          this.editType = 'add'
        }
        this.getSelect()
      })
    },
    // 获取下拉信息
    getSelect() {
      apiRuleSelect({
        is_edit: this.editType === 'add' ? 0 : 1,
        id: this.formData.id,
      }).then((res) => {
        this.loading = false
        const { dept, users, zone } = res.data
        this.deparmentList = dept.map((item) => {
          return {
            value: item.id,
            label: item.name,
          }
        })
        this.userList = users.map((item) => {
          return {
            value: item.id,
            label: item.name,
          }
        })
        this.zoneList = zone.map((item) => {
          return {
            value: item,
            label: item,
          }
        })
        if (this.rowData) {
          for (let key in this.formData) {
            this.formData[key] = this.rowData[key]
          }
          this.formData.zone_province_list = this.formData.zone_province.split(',')
          let range_name = this.rowData.range_name.split(',')
          if (range_name.length > 0) {
            range_name = range_name.map((item) => {
              if (this.formData.use_range === 1) {
                const temp = this.deparmentList.find((dept) => {
                  return dept.label === item
                })
                if (temp) {
                  return temp.value
                }
              } else {
                const temp = this.userList.find((dept) => {
                  return dept.label === item
                })
                if (temp) {
                  return temp.value
                }
              }
            })
          }
          this.formData.range_ids = range_name
        }
        if (this.formData.use_range === 2) {
          this.selectList = this.userList
        } else {
          this.selectList = this.deparmentList
        }
      })
    },
    handleRadioChange(value) {
      this.formData.range_ids = []
      if (value === 1) {
        this.selectList = this.deparmentList
      } else {
        this.selectList = this.userList
      }
    },
    // 关闭弹出层
    cancelForm() {
      this.clearData()
      this.drawer = false
    },
    // 清除表格
    clearData() {
      this.$refs.ruleForm.resetFields()
    },
    // 提交
    formDataSubmit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          this.formData.zone_province = this.formData.zone_province_list.join(',')
          this.loading = true
          if (this.editType === 'add') {
            apiRuleAdd(this.formData)
              .then((res) => {
                this.loading = false
                if (res.code !== 200) {
                  return
                }
                this.$message({
                  type: 'success',
                  message: '添加成功',
                })
                this.$emit('refreshList')
                setTimeout(() => {
                  this.drawer = false
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            apiRuleEdit(this.formData)
              .then((res) => {
                this.loading = false
                if (res.code !== 200) {
                  return
                }
                this.$message({
                  type: 'success',
                  message: '修改成功',
                })
                this.$emit('refreshList')
                setTimeout(() => {
                  this.drawer = false
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          }
        }
      })
    },
  },
}
</script>
<style lang="scss">
.tips {
  margin-left: 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 14px;
  color: #666;
  i {
    margin-right: 4px;
  }
}
.unit {
  margin-left: 16px;
  font-size: 14px;
  color: #666;
}
.el-divider--horizontal {
  margin: 8px 0;
}
</style>
